﻿var map, mapOptions;
var markers     = new Array();
var rosario     = new google.maps.LatLng(-32.94, -60.6597);
var cordoba     = new google.maps.LatLng(-31.39357856290326, -64.18493270874023);
var bsas        = new google.maps.LatLng(-34.63949615862544, -58.491439819335945);
var ciudadesControl, ciudadesControlDiv, vehiculosControl, vehiculosControlDiv;
var circuloSeleccion    = null; // una variable que contiene un circulo
var keySeleccion        = '';   // una variable que contiene la clave del marker seleccionado

// markers
function markersDeleteAll() {
    for (var index in markers) {
        if (markers[index] != null) {
            markers[index].setMap(null);
            markers[index] = null;
            delete markers[index];
        }
    }
}

function markersDelete(key) {
    console.log('delete ovni ' + key);
    if (markers[key] != null) {
        markers[key].setMap(null);
        markers[key] = null;
        delete markers[key];
    }
}

function markersInsertOrUpdate (key, lat, lon) {
    if (markers[key] == null) {
        console.log('insert ovni ' + key);
        
        markers[key] = new google.maps.Marker({
            position    : new google.maps.LatLng(lat, lon),
            map         : map,
            title       : key,
            icon        : 'img/brio_ver03.ico'
        });

        google.maps.event.addListener   (markers[key], 'click', function() {
            vehiculosControl.setTxtSim  ('SIM ' + markers[key].title);

            if (circuloSeleccion != null) {
                circuloSeleccion.setMap(null);
                circuloSeleccion = null;
            }

            var circuloOptions = {
                strokeColor     : 'Yellow',
                strokeOpacity   : 0.8,
                strokeWeight    : 2,
                fillColor       : 'LimeGreen',
                fillOpacity     : 0.35,
                map             : map,
                center          : markers[key].position,
                radius          : getRadioCirculoSeleccion ()
            };

            circuloSeleccion = new google.maps.Circle(circuloOptions);
            circuloSeleccion.bindTo ('center', markers[key], 'position');
            keySeleccion = key;
        });
        
    } else {
        console.log('update ovni ' + key);
        
        markers[key].setPosition (
            new google.maps.LatLng(lat, lon)
        );
    }   
}

function getRadioCirculoSeleccion() { 
    return getZoomFactor(map.getZoom()) / 200;
}

function getZoomFactor (zoom) {
    if (zoom == 20) return 1128.497220;
    if (zoom == 19) return 2256.994440;
    if (zoom == 18) return 4513.988880;
    if (zoom == 17) return 9027.977761;
    if (zoom == 16) return 18055.955520;
    if (zoom == 15) return 36111.911040;
    if (zoom == 14) return 72223.822090;
    if (zoom == 13) return 144447.644200;
    if (zoom == 12) return 288895.288400;
    if (zoom == 11) return 577790.576700;
    if (zoom == 10) return 1155581.153000;
    if (zoom == 9) return 2311162.307000;
    if (zoom == 8) return 4622324.614000;
    if (zoom == 7) return 9244649.227000;
    if (zoom == 6) return 18489298.450000;
    if (zoom == 5) return 36978596.910000;
    if (zoom == 4) return 73957193.820000;
    if (zoom == 3) return 147914387.600000;
    if (zoom == 2) return 295828775.300000;
    if (zoom == 1) return 591657550.500000;
    else return 0;
}

// ajax
function getResponseText(method, url, async, func) {
    var xmlhttp;

    if (window.XMLHttpRequest) {
        xmlhttp = new XMLHttpRequest(); // IE7+, Firefox, Chrome, Opera, Safari
    } else {
        xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); // IE6, IE5
    }
    xmlhttp.onreadystatechange = function() {
        if ((xmlhttp.readyState == 4) && (xmlhttp.status == 200)) {
            func(xmlhttp.responseText);
        }
    }
    xmlhttp.open(method, url, async);
    xmlhttp.send(); // para post se puede mandar un string aca.
}

function ClickableCtrl (controlDiv, map, texto, tooltip, onclickfn) {
    controlDiv.style.padding            = '5px';
    var controlUI                       = document.createElement('DIV');
    controlUI.style.backgroundColor     = 'SteelBlue';
    controlUI.style.borderStyle         = 'solid';
    controlUI.style.borderWidth         = '2px';
    controlUI.style.cursor              = 'pointer';
    controlUI.style.textAlign           = 'center';
    controlUI.title                     = tooltip;
    controlDiv.appendChild (controlUI);
    
    var controlText                     = document.createElement('DIV');
    controlText.style.fontFamily        = 'Arial,sans-serif';
    controlText.style.fontSize          = '12px';
    controlText.style.paddingLeft       = '4px';
    controlText.style.paddingRight      = '4px';
    controlText.innerHTML               = texto;
    controlUI.appendChild (controlText);
    google.maps.event.addDomListener (controlUI, 'click', onclickfn);
}

function CiudadesControl (controlDiv, map) {
    var colorNormal                 = 'WhiteSmoke';
    var colorResaltado              = /*'LightSkyBlue'*/ 'OrangeRed';
    var colorBordeExterior          = 'Silver';
    var colorBordeInterior          = 'Silver';
    
    controlDiv.style.padding        = '5px';
    
    var controlUI                   = document.createElement('DIV');
    controlUI.style.backgroundColor = colorNormal;
    controlUI.style.borderStyle     = 'solid';
    controlUI.style.borderColor     = colorBordeExterior;
    controlUI.style.borderWidth     = '1px';
    controlUI.style.cursor          = 'pointer';
    controlUI.style.textAlign       = 'center';
    controlUI.style.width           = '82px'; 
    controlDiv.appendChild (controlUI);
    
    var ctrlBsAs                    = document.createElement('DIV');
    ctrlBsAs.style.fontFamily       = 'Arial,sans-serif';
    ctrlBsAs.style.borderStyle      = 'solid';
    ctrlBsAs.style.borderWidth      = '1px';
    ctrlBsAs.style.borderColor      = colorBordeInterior;
    ctrlBsAs.style.fontSize         = '11px';
    ctrlBsAs.style.paddingLeft      = '4px';
    ctrlBsAs.style.paddingRight     = '4px';
    ctrlBsAs.innerHTML              = 'Bs. As.';
    google.maps.event.addDomListener(ctrlBsAs, 'click'     , function() { map.setCenter(bsas); map.setZoom(10);    });
    google.maps.event.addDomListener(ctrlBsAs, 'mouseover' , function() { ctrlBsAs.style.backgroundColor = colorResaltado; });
    google.maps.event.addDomListener(ctrlBsAs, 'mouseout'  , function() { ctrlBsAs.style.backgroundColor = colorNormal; });
    controlUI.appendChild           (ctrlBsAs);
    
    var ctrlCordoba                 = document.createElement('DIV');
    ctrlCordoba.style.fontFamily    = 'Arial,sans-serif';
    ctrlCordoba.style.borderStyle   = 'solid';
    ctrlCordoba.style.borderWidth   = '1px';
    ctrlCordoba.style.borderColor   = colorBordeInterior;
    ctrlCordoba.style.fontSize      = '11px';
    ctrlCordoba.style.paddingLeft   = '4px';
    ctrlCordoba.style.paddingRight  = '4px';
    ctrlCordoba.innerHTML           = 'Córdoba';
    google.maps.event.addDomListener(ctrlCordoba, 'click'     , function() { map.setCenter(cordoba); map.setZoom(12);    });
    google.maps.event.addDomListener(ctrlCordoba, 'mouseover' , function() { ctrlCordoba.style.backgroundColor = colorResaltado; });
    google.maps.event.addDomListener(ctrlCordoba, 'mouseout'  , function() { ctrlCordoba.style.backgroundColor = colorNormal; });
    controlUI.appendChild           (ctrlCordoba);
    
    var ctrlRosario                 = document.createElement('DIV');
    ctrlRosario.style.fontFamily    = 'Arial,sans-serif';
    ctrlRosario.style.borderStyle   = 'solid';
    ctrlRosario.style.borderWidth   = '1px';
    ctrlRosario.style.borderColor   = colorBordeInterior;
    ctrlRosario.style.fontSize      = '11px';
    ctrlRosario.style.paddingLeft   = '4px';
    ctrlRosario.style.paddingRight  = '4px';
    ctrlRosario.innerHTML           = 'Rosario';
    google.maps.event.addDomListener(ctrlRosario, 'click'     , function() { map.setCenter(rosario); map.setZoom(12);    });
    google.maps.event.addDomListener(ctrlRosario, 'mouseover' , function() { ctrlRosario.style.backgroundColor = colorResaltado; });
    google.maps.event.addDomListener(ctrlRosario, 'mouseout'  , function() { ctrlRosario.style.backgroundColor = colorNormal; });
    controlUI.appendChild           (ctrlRosario);
}

VehiculosControl.prototype.divSIM_              = document.createElement ('DIV');
VehiculosControl.prototype.getTxtSim            = function( )   { return this.divSIM_.innerHTML; }
VehiculosControl.prototype.setTxtSim            = function(s)   { this.divSIM_.innerHTML = s; }

VehiculosControl.prototype.divVel_              = document.createElement('DIV');
VehiculosControl.prototype.getTxtVel            = function( )   { return this.divVel_.innerHTML; }
VehiculosControl.prototype.setTxtVel            = function(s)   { this.divVel_.innerHTML = s; }

VehiculosControl.prototype.divTipoVehiculo_     = document.createElement ('DIV');
VehiculosControl.prototype.getTxtTipoVehiculo   = function( )   { return this.divTipoVehiculo_.innerHTML; }
VehiculosControl.prototype.setTxtTipoVehiculo   = function(s)   { this.divTipoVehiculo_.innerHTML = s; }

VehiculosControl.prototype.divSeguir_           = document.createElement('DIV');

VehiculosControl.prototype.seguir_              = false;
VehiculosControl.prototype.getSeguir            = function( )       { return this.seguir_; }
VehiculosControl.prototype.setSeguir            = function(seguir) {
    this.seguir_ = seguir;
    if (this.seguir_) {
        this.divSeguir_.innerHTML = 'Dejar';
        if (keySeleccion != '')
            map.setCenter (markers[keySeleccion].position);
    } else {
        this.divSeguir_.innerHTML = 'Seguir';
    }
}

function VehiculosControl (controlDiv, map) {
    var colorNormal                 = 'WhiteSmoke';
    var colorResaltado              = /*'LightSkyBlue'*/'OrangeRed';
    var colorBordeExterior          = 'Silver';
    var colorBordeInterior          = 'Silver';

    controlDiv.style.padding        = '5px';

    var controlUI                   = document.createElement('DIV');
    controlUI.style.backgroundColor = colorNormal;
    controlUI.style.borderStyle     = 'solid';
    controlUI.style.borderColor     = colorBordeExterior;
    controlUI.style.borderWidth     = '1px';
    controlUI.style.cursor          = 'pointer';
    controlUI.style.textAlign       = 'center';
    controlUI.style.width           = '200px';
    controlUI.style.height          = '78px';
    controlDiv.appendChild          (controlUI);

    var controlDivImgChofer                 = document.createElement('DIV');
    controlDivImgChofer.style.borderStyle   = 'solid';
    controlDivImgChofer.style.borderColor   = colorBordeExterior;
    controlDivImgChofer.style.borderWidth   = '1px';
    controlDivImgChofer.style.cursor        = 'pointer';
    controlDivImgChofer.style.width         = '50px';
    controlDivImgChofer.style.height        = '50px';
    controlDivImgChofer.style.position      = 'relative';
    controlDivImgChofer.style.top           = '3px';
    controlDivImgChofer.style.left          = '3px';
    controlUI.appendChild                   (controlDivImgChofer);

    var controlImgChofer                    = document.createElement('IMG');
    controlImgChofer.border                 = '0px';
    controlImgChofer.src                    = 'img/vehiculos/ducato.jpg';
    controlImgChofer.width                  = 50;
    controlImgChofer.height                 = 50;
    controlDivImgChofer.appendChild         (controlImgChofer);

    this.divTipoVehiculo_.style.position    = 'absolute';
    this.divTipoVehiculo_.style.top         = '10px';
    this.divTipoVehiculo_.style.left        = '63px';
    this.divTipoVehiculo_.innerHTML         = 'Fiat Ducato - Nro ...';
    this.divTipoVehiculo_.style.fontFamily  = 'Arial,sans-serif';
    this.divTipoVehiculo_.style.fontSize    = '11px';
    controlUI.appendChild                   (this.divTipoVehiculo_);

    this.divSIM_.style.position             = 'absolute';
    this.divSIM_.style.top                  = '24px';
    this.divSIM_.style.left                 = '63px';
    this.divSIM_.innerHTML                  = 'SIM ...';
    this.divSIM_.style.fontFamily           = 'Arial,sans-serif';
    this.divSIM_.style.fontSize             = '11px';
    controlUI.appendChild(this.divSIM_);

    this.divVel_.style.position             = 'absolute';
    this.divVel_.style.top                  = '38px';
    this.divVel_.style.left                 = '63px';
    this.divVel_.innerHTML                  = '0 Kph';
    this.divVel_.style.fontFamily           = 'Arial,sans-serif';
    this.divVel_.style.fontSize             = '11px';
    controlUI.appendChild(this.divVel_);
    
    this.divSeguir_.style.fontFamily    = 'Arial,sans-serif';
    this.divSeguir_.style.borderStyle   = 'solid';
    this.divSeguir_.style.borderWidth   = '1px';
    this.divSeguir_.style.borderColor   = colorBordeInterior;
    this.divSeguir_.style.fontSize      = '11px';
    this.divSeguir_.style.position      = 'absolute';
    this.divSeguir_.style.top           = '60px';
    this.divSeguir_.style.left          = '9px';
    this.divSeguir_.style.width         = '50px';
    this.divSeguir_.innerHTML           = 'Seguir';
    google.maps.event.addDomListener    (this.divSeguir_, 'click', function() {
        vehiculosControl.setSeguir      (! vehiculosControl.getSeguir());
    });
    google.maps.event.addDomListener    (this.divSeguir_, 'mouseover', function() { /*aca this es divSeguir_ */ this.style.backgroundColor = colorResaltado; });
    google.maps.event.addDomListener    (this.divSeguir_, 'mouseout' , function() { /*aca this es divSeguir_ */ this.style.backgroundColor = colorNormal; });
    controlUI.appendChild               (this.divSeguir_);
}

var fmarkers = function() {
    getResponseText("GET", "http://www.televoyeur.com/ovnis.aspx", true, function(respuesta) {
        //si es chrome o firefox se puede usar esto -> var objs = JSON.parse (respuesta);
        var objs = eval('(' + respuesta + ')');

        for (var index in objs.ovnis) {
            //markersDelete   (key);
            markersInsertOrUpdate(
                objs.ovnis[index].key,
                objs.ovnis[index].lat,
                objs.ovnis[index].lon
            );

            //  centro el mapa si
            //      key == keySeleccion                                             &&
            //      el boton "seguir" del control de vehiculos está activado        &&
            //      el centro del mapa es distinto que el centro que quiero poner
            var keyX = objs.ovnis[index].key;

            if (keyX == keySeleccion) {
                console.log('keySeleccion == ' + keyX);
                console.log('seguir == ' + vehiculosControl.getSeguir());

                if (! map.getCenter().equals(markers[keyX].position) && (vehiculosControl.getSeguir())) {
                    console.log('centrado mapa con ' + keyX);
                    map.setCenter(markers[keyX].position);
                }
            }

            if (keyX == keySeleccion) {
                vehiculosControl.setTxtVel('' + objs.ovnis[index].vel + ' KpH');
            }
        }
    });

    console.log('mandé request asíncrona...');
}

// init
var iniciar = function() {
    mapOptions = {
        center      : rosario,
        zoom        : 12,
        mapTypeId   : google.maps.MapTypeId.ROADMAP,
        mapTypeControl: true,
        //mapTypeControlOptions   : {
        //    style: google.maps.MapTypeControlStyle.DROPDOWN_MENU
        //},
        zoomControl: true,
        zoomControlOptions: {
            style: google.maps.ZoomControlStyle.SMALL
        },
        panControl  : false
    };

    map = new google.maps.Map(
        document.getElementById("map_canvas"),
        mapOptions
    );

    google.maps.event.addListenerOnce(map, 'idle', function() {
        fmarkers(); // llamo que se muestren los marcadores por primera vez...
    });

    google.maps.event.addListener(map, 'zoom_changed', function() {
        if (circuloSeleccion != null)
            circuloSeleccion.radius = getRadioCirculoSeleccion();    
    });
    
    self.setInterval(fmarkers, 5000); // hago que se actualizen los marcadores cada 5 segundos

    // control de ciudades
    ciudadesControlDiv = document.createElement('DIV');
    ciudadesControl = new CiudadesControl(ciudadesControlDiv, map);
    ciudadesControlDiv.index = 1;
    map.controls[google.maps.ControlPosition.RIGHT_TOP].push(ciudadesControlDiv);

    // control de vehículos
    vehiculosControlDiv = document.createElement('DIV');
    vehiculosControl = new VehiculosControl(vehiculosControlDiv, map);
    vehiculosControlDiv.index = 2;
    map.controls[google.maps.ControlPosition.TOP_RIGHT].push(vehiculosControlDiv);
}

